package com.ziyun.erp.modules.material.service.impl;

import com.ziyun.erp.common.e.material.MaterialStatusEnum;
import com.ziyun.erp.modules.material.entity.dto.StoreStockMaterialDto;
import io.renren.common.exception.RRExceptionHandler;
import io.renren.common.utils.R;
import io.renren.common.utils.StringUtil;
import com.ziyun.erp.common.utils.UserUtils;
import com.ziyun.erp.modules.material.service.MaterialCategoryService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import com.ziyun.erp.modules.material.dao.MaterialDao;
import com.ziyun.erp.modules.material.entity.MaterialEntity;
import com.ziyun.erp.modules.material.service.MaterialService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;


@Service("materialService")
public class MaterialServiceImpl extends ServiceImpl<MaterialDao, MaterialEntity> implements MaterialService {

    @Autowired
    private MaterialCategoryService materialCategoryService;

    //  查询出原材料耗材库列表
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = "categoryId";
        String key2 = "materialName";
        if(params.containsKey(key)&&params.containsKey(key2)&&params.get("categoryId")!=""){
            Iterator<String> iterator = params.keySet().iterator();
            while(iterator.hasNext()){
                String kesy = iterator.next();
                if("materialName".equals(kesy)){
                    iterator.remove();
                }
            }
        }
        boolean contains2 = params.containsKey(key2);
        if(contains2){
            int totalCount = 0;
            Object obj = params.get("materialName");
            String materialName = obj.toString();
            totalCount = baseMapper.getqueryCountByname(materialName);
            int current = Integer.valueOf((String) params.get("page"));
            int size = Integer.valueOf((String) params.get("limit"));
            params.put("offset", (current - 1) * size);
            params.put("limit", size);
            List<MaterialEntity> list = baseMapper.getQueryListByname(params);
            return new PageUtils(list, totalCount, size, current);
        }
        boolean contains = params.containsKey(key);
        if (contains) {
            Integer categoryId = null;
            int totalCount = 0;
            Object obj = params.get("categoryId");
            int BM = 1;
            int BT = Integer.parseInt(String.valueOf(obj));
            int BJ = 0;
            if(BT == BJ){
                int i = baseMapper.getqueryCountBycategoryId();
                int current = Integer.valueOf((String) params.get("page"));
                int size = Integer.valueOf((String) params.get("limit"));
                params.put("offset", (current - 1) * size);
                params.put("limit", size);
                List<MaterialEntity> list = baseMapper.getQueryListBycategoryId(params);
                return new PageUtils(list, i, size, current);
            }
            totalCount = baseMapper.getqueryCount(BT);
            int current = Integer.valueOf((String) params.get("page"));
            int size = Integer.valueOf((String) params.get("limit"));
            params.put("offset", (current - 1) * size);
            params.put("limit", size);
            List<MaterialEntity> list = baseMapper.getQueryList(params);
            return new PageUtils(list, totalCount, size, current);
        } else {
            int totalCount = baseMapper.getqueryCount2();
            int current = Integer.valueOf((String) params.get("page"));
            int size = Integer.valueOf((String) params.get("limit"));
            params.put("offset", (current - 1) * size);
            params.put("limit", size);
            List<MaterialEntity> list = baseMapper.getQueryList2(params);
            return new PageUtils(list, totalCount, size, current);
        }
    }

    @Override
    public void deleteUpdateById(Integer materialId, Long userId) {
        Map<String,Object> updateMap = new HashMap<>();
        updateMap.put("delete",1);
        updateMap.put("update_name",userId);
        baseMapper.updateByMap(updateMap,materialId);
    }

    @Override
    public void auditById(Integer materialId) {
        Map<String,Object> updateMap = new HashMap<>();
        updateMap.put("audit_time",new Date());
        updateMap.put("audit_name",UserUtils.getCurentUser().getUsername());
        updateMap.put("update_name",UserUtils.getCurentUser().getUsername());
        updateMap.put("status",MaterialStatusEnum.ALREADY_AUDIT.toInt());

        baseMapper.updateByMap(updateMap,materialId);
    }

    @Override
    public void queryMaterialsListPage(Page<MaterialEntity> page, Map<String, Object> params) {
        page.setRecords(baseMapper.queryMaterialsListPage(page,params));
    }

    @Override
    public int getparentId(Integer categoryId) {
        return baseMapper.getParentId(categoryId);
    }

    @Override
    public String selectMaterialId(String materialCode) {
        return baseMapper.getMaterialId(materialCode);
    }

    // 生成MaterialCode(耗材编号)
    @Override
    public String CreateMaterialCode(int ParentId, int CategoryId) {
        StringBuilder material_code = new StringBuilder("M");
        if(CategoryId < 10) {
            material_code.append("00");
            material_code.append(ParentId);
        }else if(ParentId >= 10 && ParentId < 100) {
            material_code.append("0");
            material_code.append(ParentId);
        }else {
            material_code.append(ParentId);
        }
        if(CategoryId < 10) {
            material_code.append("00");
            material_code.append(CategoryId);
        }else if(CategoryId >= 10 && CategoryId < 100) {
            material_code.append("0");
            material_code.append(CategoryId);
        }else {
            material_code.append(CategoryId);
        }

        //取3位随机数
        int rand = (int)(Math.random()*900 + 100);
        material_code.append(rand);

        return material_code.toString();
    }

    @Override
    public int saveMaterialByStockId(Integer stockId, String materialId, BigDecimal cost) {
        return baseMapper.saveMaterialByStockId(stockId,materialId,cost);
    }

    @Override
    public Integer selectStockId(Integer sellerId) {

        return baseMapper.getStockId(sellerId);

    }
    @Override
    public R saveStoreStockMaterialBystockId(Integer sellerId,String materialId,BigDecimal cost) throws Exception {
            Integer stockId = baseMapper.getStockId(sellerId);
            try{
                baseMapper.saveMaterialByStockId(stockId,materialId,cost);
            }catch (Exception e){
                throw new Exception("仓库ID不能为空");
             }
        return R.ok();
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R saveMaterialAndStoreStockMaterial(StoreStockMaterialDto storeStockMaterialDto) throws Exception {
        MaterialEntity materialEntity = storeStockMaterialDto.getMaterialEntity();
        try {
            baseMapper.insert(materialEntity);
        }catch (Exception e){
            throw new Exception("插入数据失败");
        }
        String materialId = baseMapper.getMaterialId(materialEntity.getMaterialCode());
        for(int i = 0;i<storeStockMaterialDto.getSellerInfoEntity().size();i++){
            int sellerId = storeStockMaterialDto.getSellerInfoEntity().get(i).getSellerId();
            Integer stockId = baseMapper.getStockId(sellerId);
            BigDecimal cost =storeStockMaterialDto.getSellerInfoEntity().get(i).getCost();
            try{
            baseMapper.saveMaterialByStockId(stockId,materialId,cost);
            }catch (Exception e){
                throw new Exception("插入数据失败,请维护对应的仓库Id");
            }
        }
        return R.ok();
    }
}
